﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using Common;

namespace School.Admin.Admin
{
    public partial class EditPic : CheckPower
    {
        #region 传递参数
        public int ID
        {
            get
            {
                if (Request.QueryString["id"] == null || Request.QueryString["id"] == "")
                {
                    return 0;
                }
                return int.Parse(Request.QueryString["id"].ToString());
            }
        }
        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (ID > 0)
                {
                    Model.UserPic c = new BLL.UserPic().GetModel(ID);
                    TextBox1.Text = c.ImgName;
                    RadioButtonList1.SelectedValue = c.State.ToString();
                    ImageView.ImageUrl = c.ImgURL;
                }
            }
        }

        #region 防止更改后缀上传
        public class FileValidation
        {
            public static bool IsAllowedExtension(FileUpload fu, FileExtension[] fileEx)
            {
                //得到文件大小
                int fileLen = fu.PostedFile.ContentLength;
                byte[] imgArray = new byte[fileLen];
                //读取字节数
                fu.PostedFile.InputStream.Read(imgArray, 0, fileLen);
                MemoryStream ms = new MemoryStream(imgArray);
                System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
                string fileclass = "";
                byte buffer;
                //得到文件二进制流
                try
                {
                    buffer = br.ReadByte();
                    fileclass = buffer.ToString();
                    buffer = br.ReadByte();
                    fileclass += buffer.ToString();
                }
                catch
                {
                }
                br.Close();
                ms.Close();
                //相比较
                foreach (FileExtension fe in fileEx)
                {
                    if (Int32.Parse(fileclass) == (int)fe)
                        return true;
                }
                return false;
            }
        }
        #endregion

        #region 定义文件二进制流
        public enum FileExtension
        {
            // 255216 jpg;// 7173 gif;// 6677 bmp, // 13780 png// 6787 swf // 7790 exe dll,// 8297 rar// 8075 zip// 55122 7z
            // 6063 xml // 6033 html // 239187 aspx // 117115 cs // 119105 js // 102100 txt  // 255254 sql        
            JPG = 255216,
            GIF = 7173,
            PNG = 13780,
            BMP = 6677,
            RAR = 8297,
            TXT = 1310,
            DOC = 208207,
            DOCX = 208207,
            XLS = 8075,
            XLSX = 8075,
            PPT = 8075,
            PPTX = 8075
        }
        #endregion

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (FileUploadPicture.HasFile)
            {
                string oldFileName = Utility.FileUploads.GetFileName(FileUploadPicture.FileName);
                if (FileUploadPicture.PostedFile != null && FileUploadPicture.PostedFile.ContentLength > 0)
                {
                    int ImgSize = FileUploadPicture.PostedFile.ContentLength;//此处取得的文件大小的单位是byte
                    if (ImgSize / 1024 < 4000)//文件大小不能超过4M
                    {
                        string imageType = Path.GetExtension(FileUploadPicture.PostedFile.FileName).ToLower();//获取图片格式
                        //检查后缀名
                        if (imageType != ".jpg" && imageType != ".jpeg" && imageType != ".bmp" && imageType != ".gif" && imageType != ".png")
                        {
                            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "<script> alert('上传文件格式错误！');</script>", false);
                            return;
                        }
                        //防止更改后缀上传
                        FileExtension[] fe = { FileExtension.GIF, FileExtension.JPG, FileExtension.PNG, FileExtension.BMP };
                        //调用方法比较文件二进制流
                        if (!FileValidation.IsAllowedExtension(FileUploadPicture, fe))
                        {
                            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "<script> alert('上传文件格式错误！');</script>", false);
                            return;
                        }
                        string newFileName = Utility.FileUploads.NewFileName(oldFileName);
                        FileUploadPicture.SaveAs(Server.MapPath("/Uploads/" + newFileName));
                        ImageView.ImageUrl = "/Uploads/" + newFileName;
                        lbPic.Text = "/Uploads/" + newFileName;
                    }
                    else
                    {
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "<script> alert('文件大小超过4M！请重新上传!');</script>", false);
                        return;
                    }
                }
            }
        }

        public void btnSave_Click(object sender, EventArgs e)
        {
            if (ID > 0)
            {
                Model.UserPic c = new BLL.UserPic().GetModel(ID);
                if (RadioButtonList1.SelectedValue == "0")
                {
                    if (ID == 1)
                    {
                        ScriptHelper.Alert("默认头像不能禁用！");
                        return;
                    }
                }
                c.ImgName = TextBox1.Text;
                c.State = int.Parse(RadioButtonList1.SelectedValue);
                if (!string.IsNullOrEmpty(lbPic.Text))
                {
                    string locatPath = Server.MapPath(c.ImgURL);
                    //是否存在此文件
                    if (File.Exists(locatPath))
                    {
                        //删除相对应的文件
                        File.Delete(locatPath);
                    }
                    c.ImgURL = ImageView.ImageUrl;
                }
                if (new BLL.UserPic().Update(c))
                {
                    lbPic.Text = "";
                    ScriptHelper.Alert("修改成功！");
                }
            }
            else
            {
                Model.UserPic c = new Model.UserPic();
                c.State = int.Parse(RadioButtonList1.SelectedValue);
                c.ImgURL = ImageView.ImageUrl;
                if (new BLL.UserPic().Add(c) > 0)
                {
                    ScriptHelper.AlertRedirect("增加成功！", "UserPic.aspx");
                }
            }
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            Response.Redirect("UserPic.aspx");
        }
    }
}